package chat.client;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Vector;


import chat.ui.ChatHandler;
import chat.ui.GroupChatWindow;
import chat.user.Group;
import chat.user.Message;
import chat.user.MessageCreator;

public class ClientMain implements Runnable {
	
	private static Queue<Message> InMessageList = new LinkedList<Message>();
	private static Queue<Message> OutMessageList = new LinkedList<Message>();
	private Socket fromserver;
	private GroupChatWindow chat_window;
	
	public ClientMain(GroupChatWindow chat) throws Exception{
		
		chat_window = chat;
		
		try {
			
			fromserver = new Socket("localhost", 4444);
		}
		catch(IOException e){
			
			e.printStackTrace();
			System.out.println("Cannot connect to server");
		}
			
		new Thread(new ClientRequestor(fromserver)).start();
		new Thread(new ClientReceiver(fromserver)).start();
	}
	
	@Override
	public synchronized void run(){
		
		try {
			
			for (;;Thread.sleep(500)){
			
			for ( ; getInMessageCount()>0; ){
					
					Message m = getInMessage();
					
					if (m.AUTH_REQUEST){
						
						chat_window.setUser(m.getUser());
						
						ClientMain.addOutMessage(MessageCreator.createUpdateGroupMessage(chat_window.getUser()));
						
						System.out.println();
					}
					
					if (m.GROUP_UPDATE){
						
						Vector<String> g_names = m.getGroupNames();
						
						for (String p: g_names){
							
							if (!p.equalsIgnoreCase("ROOT")){
							
								chat_window.addNewItem(p);
							}
						}
					}
					
					if (m.SEND_MESSAGE){
						
						ChatHandler.setTextFromMessage(m.getMessage(), chat_window.getChat());
						
					}
					
					if (m.NEW_GROUP_REQUEST){
						
						chat_window.addNewItem(m.getGroup());
					}
					
					if (m.CONNECT_TO_GROUP){
						
						chat_window.getUser().updateRelatedGroup(m.getGroup());
					}
					
					ClientMain.removeInMessage(m);
				}
			}
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
	}
	
	public static boolean addInMessage(Message m){
		
		return InMessageList.add(m);
	}
	
	public static boolean removeInMessage(Message m){
		
		return InMessageList.remove(m);
	}
	
	public static boolean addOutMessage(Message m){
		
		return OutMessageList.add(m);
	}
	
	public static boolean removeOutMessage(Message m){
		
		return OutMessageList.remove(m);
	}
	
	public static Message getInMessage(){
		
		return InMessageList.peek();
	}
	
	public static Message getOutMessage(){
		
		return OutMessageList.peek();
	}
	
	public static int getInMessageCount(){
		return InMessageList.size();
	}
	
	public static int getOutMessageCount(){
		return OutMessageList.size();
	}
}
